package com.reshare.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.reshare.base.BaseService;
import com.reshare.bean.User;
import com.reshare.bean.UserRole;
import com.reshare.mapper.RoleMapper;
import com.reshare.mapper.UserMapper;
import com.reshare.mapper.UserRoleMapper;
import com.reshare.model.UserModel;
import com.reshare.query.UserQuery;
import com.reshare.utils.AssertUtil;
import com.reshare.utils.Md5Util;
import com.reshare.utils.PhoneUtil;
import com.reshare.utils.UserIDBase64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.*;

@Service
public class UserService extends BaseService<User, Integer> {


    @Autowired(required = false)
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;


    //注册
    public void userRegister(String userName, String userPwd) {
        //验证
        checkLoginParams(userName,userPwd);
        //密码加密
        userPwd=Md5Util.encode(userPwd);
        //用户是否存在
        User user = new User();
        if(!userName.equals(user.getUserName())){
            //进行赋值
            user.setUserName(userName);
            user.setUserPwd(userPwd);
            //判断是否能注册成功
            AssertUtil.isTrue(userMapper.insertSelective(user) < 1, "注册失败了");
        }else {

        }
    }

    //登录
    public UserModel userLogin(String userName, String userPwd) {
        //校验用户和密码
        checkLoginParams(userName, userPwd);
        //判断用户是否存在
        User user = userMapper.selectUserByName(userName);
        AssertUtil.isTrue(user == null, "用户不存在");
        //密码校验
        checkLoginPwd(userPwd, user.getUserPwd());
        //构建返回对象
        return buildUser(user);
    }


    private UserModel buildUser(User user) {
        //实例化对象
        UserModel userModel = new UserModel();
        //加密
        //对id进行加密
        String userId = UserIDBase64.encoderUserID(user.getId());
        //将加密后的id，用户名，真实密码存储到userModel
        userModel.setUserIdStr(userId);
        userModel.setUserName(user.getUserName());
        userModel.setTrueName(user.getTrueName());
        //返回
        return userModel;
    }


    private void checkLoginPwd(String userPwd, String userPwd1) {
        //将输入的密码加密
        userPwd = Md5Util.encode(userPwd);
        //比对密码是否正确
        AssertUtil.isTrue(!(userPwd.equals(userPwd1)), "用户密码不正确");
    }

    private void checkLoginParams(String userName, String userPwd) {
        //用户名不能为空
        AssertUtil.isTrue(StringUtils.isBlank(userName), "用户名不能为空");
        //密码不能为空
        AssertUtil.isTrue(StringUtils.isBlank(userPwd), "密码不能为空");
    }

    public void changePwd(Integer userId,String oldPwd,String newPwd,String confirmPwd){
        //获取信息
        User user = userMapper.selectByPrimaryKey(userId);
        //验证用户与密码
        checkUserPassword(user,oldPwd,newPwd,confirmPwd);
        //加密并修改
        user.setUserPwd(Md5Util.encode(newPwd));
        //判断是否成功
        AssertUtil.isTrue(userMapper.updateByPrimaryKeySelective(user)<1,"密码修改失败");
    }
    private void checkUserPassword(User user, String oldPwd, String newPwd, String confirmPwd) {
        //旧密码不能为空
        AssertUtil.isTrue(oldPwd==null,"原密码不能为空");
        //旧密码要正确
        AssertUtil.isTrue(user.getUserPwd().equals(oldPwd),"原密码不正确");
        //新密码不能为空
        AssertUtil.isTrue(newPwd==null,"新密码不能为空");
        //新密码与旧密码不能相同
        AssertUtil.isTrue(newPwd.equals(oldPwd),"新密码与原密码不能相同");
        //确认密码不能为空
        AssertUtil.isTrue(confirmPwd==null,"确认密码不能为空");
        //确认密码与新密码要相同
        AssertUtil.isTrue(!(confirmPwd.equals(newPwd)),"确认密码与新密码要相同");
    }

    public void changeUserSetting(Integer userId,String userName,String email,String phone,String trueName){
        //获取信息
        User user = userMapper.selectByPrimaryKey(userId);
        //验证
        checkUser(userName,email,phone);
        AssertUtil.isTrue(trueName==null,"真实姓名不能为空");
        //判断是否成功
        AssertUtil.isTrue(userMapper.updateByPrimaryKeySelective(user)<1,"修改失败");
    }


    /**
     * 查询表中数据并分页
     * @author WangYueHu
     * @date 2021/9/1 19:33
     * @param query
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    public Map<String,Object> selUser(UserQuery query){

        //初始化分页数据
        PageHelper.startPage(query.getPage(),query.getLimit());
        //查询数据
        List<User> ulist=userMapper.selectByParams(query);
        //分页
        PageInfo<User> plist=new PageInfo<>(ulist);

        Map<String,Object> map = new HashMap();
        //准备数据
        map.put("code",0);
        map.put("count",plist.getTotal());
        map.put("data",plist.getList());

        return map;
    }

    /**
     * 添加user
     * @author WangYueHu
     * @date 2021/9/1 19:33
     */
    public void saveUser(User user){
        //验证
        checkUser(user.getUserName(),user.getEmail(),user.getPhone());

        //初始化值
        user.setCreateDate(new Date());
        user.setUpdateDate(new Date());
        user.setIsValid(1);
        user.setUserPwd(Md5Util.encode("123456"));

        //是否能添加成功
        AssertUtil.isTrue(userMapper.insertSelective(user)<1,"添加失败了");

        relaionUserRole(user.getId(),user.getRoleIds());


    }

    //添加验证
    private void checkUser(String userName,String email,String phone) {
        //用户名不能为空
        AssertUtil.isTrue(StringUtils.isBlank(userName),"用户名不能为空");
        //判断是否存在该用户对象
        User temp = userMapper.selectUserByName(userName);
        AssertUtil.isTrue(temp!=null,"用户已存在");
        //Email不能为空
        AssertUtil.isTrue(StringUtils.isBlank(email),"邮箱不能为空");
        //phone不能为空     电话格式正确
        AssertUtil.isTrue(StringUtils.isBlank(phone),"手机号不能为空");
        AssertUtil.isTrue(!PhoneUtil.isMobile(phone),"手机号格式不正确");
    }


    /**
     * 更新user
     * @author WangYueHu
     * @date 2021/9/1 20:56
     * @param user
     */
    public void updateUser(User user){
        //判断用户Id是否存在
        User temp = userMapper.selectByPrimaryKey(user.getId());
        AssertUtil.isTrue(temp==null,"待修该的记录不存在");
        //验证
        checkUser1(user.getUserName(),user.getEmail(),user.getPhone());
        //初始化值
        user.setUpdateDate(new Date());
        //判断是否修改成功
        AssertUtil.isTrue(userMapper.updateByPrimaryKeySelective(user)<1,"更新失败了");

        //关联用户和角色的关系
        relaionUserRole(user.getId(),user.getRoleIds());
    }




    //更新验证
    private void checkUser1(String userName,String email,String phone) {
        //用户名不能为空
        AssertUtil.isTrue(StringUtils.isBlank(userName), "用户名不能为空");
        //判断是否存在该用户对象
        User temp = userMapper.selectUserByName(userName);
        AssertUtil.isTrue(temp == null, "编辑用户不存在");
        //Email不能为空
        AssertUtil.isTrue(StringUtils.isBlank(email), "邮箱不能为空");
        //phone不能为空     电话格式正确
        AssertUtil.isTrue(StringUtils.isBlank(phone), "手机号不能为空");
        AssertUtil.isTrue(!PhoneUtil.isMobile(phone), "手机号格式不正确");
    }


    /**
     * 批量删除user
     * @author WangYueHu
     * @date 2021/9/2 9:17
     * @param ids
     */
    public void deleteUser(Integer[] ids){
        //判断ids是否为空
        AssertUtil.isTrue(ids==null || ids.length==0,"请选择删除数据");
        //判断是否删除成功
        AssertUtil.isTrue(userMapper.deleteBatch(ids)!=ids.length,"删除失败了");

        //遍历
        for (Integer userId:ids){
            int count = userRoleMapper.countUserOfRoleByUserId(userId);
            if (count>0){
                AssertUtil.isTrue(userRoleMapper.deleteUserRoleByUserId(userId)!=count,"角色删除失败");
            }
        }
    }

    /**
     * 用户赋角色
     * @author WangYueHu
     * @date 2021/9/3 8:38
     * @param userId
     * @param roleIds
     */
    private void relaionUserRole(Integer userId,String roleIds){

        //用户是否分配角色
        //如果分配角色,统计一下角色数量
        //删除原有角色,添加新角色
        int count = userRoleMapper.countUserOfRoleByUserId(userId);
        if (count>0){
            AssertUtil.isTrue(userRoleMapper.deleteUserRoleByUserId(userId)!=count,"角色分配失败");
        }
        //实例化容器list
        List<UserRole> urlist =new ArrayList<UserRole>();
        //判断是否有角色Id
        if (roleIds!=null && roleIds.length()>0){
            //实例化对象
            for (String roleId:roleIds.split(",")){
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(Integer.parseInt(roleId));
                userRole.setCreateDate(new Date());
                userRole.setUpdateDate(new Date());
                //将对象存储到容器
                urlist.add(userRole);
            }
        }

        //调用方法添加
        AssertUtil.isTrue(userRoleMapper.insertBatch(urlist)!=urlist.size(),"添加用户角色失败");

    }

}

